'use strict';

var _ = require('underscore');
var auth = require('../authControllers/user');
var resJson = require('../utils/resJson.js');
var Promise = require('bluebird');
var busboy = require('busboy');
var path = require('path');
let fs = require('fs');
var controller = {

};

var config = {
  "imageActionName": "uploadimage",
  "imageFieldName": "upfile",
  "imageMaxSize": 2048000,
  "imageAllowFiles": [".png", ".jpg", ".jpeg", ".gif", ".bmp"],
  "imageCompressEnable": true,
  "imageCompressBorder": 1600,
  "imageInsertAlign": "none",
  "imageUrlPrefix": "",
  "imagePathFormat": "../resource/images",
  "scrawlActionName": "uploadscrawl",
  "scrawlFieldName": "upfile",
  "scrawlPathFormat": "../resource/images/{yyyy}{mm}{dd}/{time}{rand:6}",
  "scrawlMaxSize": 2048000,
  "scrawlUrlPrefix": "",
  "scrawlInsertAlign": "none",
  "snapscreenActionName": "uploadimage",
  "snapscreenPathFormat": "../resource/images/{yyyy}{mm}{dd}/{time}{rand:6}",
  "snapscreenUrlPrefix": "",
  "snapscreenInsertAlign": "none",
  "catcherLocalDomain": ["127.0.0.1", "localhost"],
  "catcherActionName": "catchimage",
  "catcherFieldName": "source",
  "catcherPathFormat": "../resource/images/{yyyy}{mm}{dd}/{time}{rand:6}",
  "catcherUrlPrefix": "",
  "catcherMaxSize": 2048000,
  "catcherAllowFiles": [".png", ".jpg", ".jpeg", ".gif", ".bmp"],
  "videoActionName": "uploadvideo",
  "videoFieldName": "upfile",
  "videoPathFormat": "../resource/videos/{yyyy}{mm}{dd}/{time}{rand:6}",
  "videoUrlPrefix": "",
  "videoMaxSize": 102400000,
  "videoAllowFiles": [
    ".flv", ".swf", ".mkv", ".avi", ".rm", ".rmvb", ".mpeg", ".mpg",
    ".ogg", ".ogv", ".mov", ".wmv", ".mp4", ".webm", ".mp3", ".wav", ".mid"
  ],
  "fileActionName": "uploadfile",
  "fileFieldName": "upfile",
  "filePathFormat": "../resource/files/{yyyy}{mm}{dd}/{time}{rand:6}",
  "fileUrlPrefix": "",
  "fileMaxSize": 51200000,
  "fileAllowFiles": [
    ".png", ".jpg", ".jpeg", ".gif", ".bmp",
    ".flv", ".swf", ".mkv", ".avi", ".rm", ".rmvb", ".mpeg", ".mpg",
    ".ogg", ".ogv", ".mov", ".wmv", ".mp4", ".webm", ".mp3", ".wav", ".mid",
    ".rar", ".zip", ".tar", ".gz", ".7z", ".bz2", ".cab", ".iso",
    ".doc", ".docx", ".xls", ".xlsx", ".ppt", ".pptx", ".pdf", ".txt", ".md", ".xml"
  ],
  "imageManagerActionName": "listimage",
  "imageManagerListPath": "../resource/images",
  "imageManagerListSize": 20,
  "imageManagerUrlPrefix": "",
  "imageManagerInsertAlign": "none",
  "imageManagerAllowFiles": [".png", ".jpg", ".jpeg", ".gif", ".bmp"],
  "fileManagerActionName": "listfile",
  "fileManagerListPath": "../resource/files",
  "fileManagerUrlPrefix": "",
  "fileManagerListSize": 20,
  "fileManagerAllowFiles": [
    ".png", ".jpg", ".jpeg", ".gif", ".bmp",
    ".flv", ".swf", ".mkv", ".avi", ".rm", ".rmvb", ".mpeg", ".mpg",
    ".ogg", ".ogv", ".mov", ".wmv", ".mp4", ".webm", ".mp3", ".wav", ".mid",
    ".rar", ".zip", ".tar", ".gz", ".7z", ".bz2", ".cab", ".iso",
    ".doc", ".docx", ".xls", ".xlsx", ".ppt", ".pptx", ".pdf", ".txt", ".md", ".xml"
  ]
};

//新增资源
controller.upload = {
  method: 'all',
  route: 'ueditor',
  filter: auth.loginCheckByAjax,
  action: (req, res, next) => {
    var ActionType = req.query.action;
    let result = '';

    switch (ActionType) {
      case 'uploadimage':
      case 'uploadfile':
      case 'uploadvideo':
        uploadFile(req, res);
        break;
      case 'listimage':
        let uploadPath = path.join(__dirname, config.imagePathFormat) + '/';
        fs.readdir(uploadPath, (err, files) => {
          var total = files.length,
            list = [];
          if (total > 0)
            files.sort().splice(req.query.start, req.query.size).forEach((a, b) => {
              /^.+.\..+$/.test(a) &&
                list.push({
                  url: '/resource/images/' + a,
                  mtime: new Date(fs.statSync(uploadPath + a).mtime).getTime()
                });
            });
          res.json({ state: total === 0 ? 'no match file' : 'SUCCESS', list: list, total: total, start: req.query.start });
        });
        break;
      case 'config':
      default:
        //res.setHeader('Content-Type', 'application/json');
        result = config;
        res.json(result);
        break;
    }
    // 
  }
};

let uploadFile = (req, res) => {
  //通过请求头信息创建busboy对象
  let bb = new busboy({ headers: req.headers });
  let uploadPath = path.join(__dirname, config.imagePathFormat) + '/';
  //将流链接到busboy对象
  req.pipe(bb);
  bb.on('file', (fieldname, file, filename, encoding, mimetype) => {
    //创建一个可写流 
    let filesize = 0;
    let ext = path.extname(filename);
    let newFilename = (new Date() - 0) + ext;
    let writeStream = fs.createWriteStream(uploadPath + newFilename);

    //监听data事件，接收传过来的文件，如果文件过大，此事件将会执行多次，此方法必须写在file方法里 
    file.on('data', data => filesize = data.length)
    writeStream.on('close', () => {
      res.send(JSON.stringify({
        "originalName": filename,
        "name": newFilename,
        "url": '/resource/images/' + newFilename,
        "type": ext,
        "size": filesize,
        "state": "SUCCESS"
      }));
    });
    file.pipe(writeStream);
  });
};

module.exports = controller;